package com.Kritsana_Ding.exus_digital_output;

import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends IOIOActivity {
	
	private ToggleButton tgb;
	private TextView tvShow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		tgb = (ToggleButton) findViewById(R.id.toggleButton1);
		tvShow = (TextView) findViewById(R.id.textView1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	class Looper extends BaseIOIOLooper{
		private DigitalOutput do_PIN_1;
		private DigitalOutput do_PIN_2;
		private DigitalInput  di_PIN_3;
		private AnalogInput   ai_PIN_31;
		
		@Override
		protected void setup() throws ConnectionLostException,
				InterruptedException {
			// TODO Auto-generated method stub
			//super.setup();
			do_PIN_1 = ioio_.openDigitalOutput(1, false);
			do_PIN_2 = ioio_.openDigitalOutput(2, false);
			di_PIN_3 = ioio_.openDigitalInput(3, DigitalInput.Spec.Mode.PULL_UP);
			ai_PIN_31 = ioio_.openAnalogInput(31);
			
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Toast.makeText(getApplicationContext(), "Connected OK", Toast.LENGTH_LONG).show();
				}
			});
			
		}
		@Override
		public void loop() throws ConnectionLostException, InterruptedException {
			// TODO Auto-generated method stub
			//super.loop();
			try {
				do_PIN_1.write(tgb.isChecked());
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
			
			try {
				do_PIN_2.write(!di_PIN_3.read());
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
			
			
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					try {
						
						tvShow.setText(String.format("%.3f", ai_PIN_31.getVoltage()));
						
					} catch (InterruptedException e) {
						// TODO: handle exception
						e.printStackTrace();
					} catch (ConnectionLostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
			
			
		}
	}
	
	protected IOIOLooper createIOIOLooper() {
		return new Looper();
		
	}
	

}
